package com.gitee.melin.bee.core.jdbc.parser;

import com.gitee.melin.bee.core.jdbc.enums.DataSourceType;
import com.google.common.collect.Lists;
import java.util.List;
import org.apache.commons.lang3.StringUtils;

public class JdbcURLInfo {

    private final DataSourceType dsType;

    private final String dbUser;

    private final String dbInstance;

    private final String dbPeer;

    private final String dbOptions;

    private final List<InetPeer> inetPeers;

    private JdbcURLInfo(DataSourceType dsType, String dbUser, String dbInstance, String dbPeer, String dbOptions) {
        this.dsType = dsType;
        this.dbUser = dbUser;
        this.dbInstance = dbInstance;
        this.dbPeer = dbPeer;
        this.dbOptions = dbOptions;

        List<InetPeer> inetPeerList = Lists.newArrayList();
        if (StringUtils.isNotBlank(this.dbPeer)) {
            String[] peers = StringUtils.split(dbPeer, ",");
            for (String peer : peers) {
                String[] items = StringUtils.split(peer, ":");
                if (items.length == 2) {
                    InetPeer inetPeer = new InetPeer(items[0], Integer.parseInt(items[1]));
                    inetPeerList.add(inetPeer);
                } else if (items.length == 1) {
                    InetPeer inetPeer = new InetPeer(items[0]);
                    inetPeerList.add(inetPeer);
                }
            }
        }
        this.inetPeers = inetPeerList;
    }

    public DataSourceType getDsType() {
        return dsType;
    }

    public String getDbUser() {
        return dbUser;
    }

    public String getDbInstance() {
        return dbInstance;
    }

    public String getDbPeer() {
        return dbPeer;
    }

    public String getDbOptions() {
        return dbOptions;
    }

    public List<InetPeer> getInetPeers() {
        return inetPeers;
    }

    public static class Builder {
        private DataSourceType dsType;

        private String dbUser;

        private String dbInstance;

        private String dbPeer;

        private String dbOptions;

        public Builder(String dbPeer) {
            this.dbPeer = dbPeer;
        }

        public Builder dsType(DataSourceType dsType) {
            this.dsType = dsType;
            return this;
        }

        public Builder dbUser(String dbUser) {
            this.dbUser = dbUser;
            return this;
        }

        public Builder dbInstance(String dbInstance) {
            this.dbInstance = dbInstance;
            return this;
        }

        public Builder dbOptions(String dbOptions) {
            this.dbOptions = dbOptions;
            return this;
        }

        public JdbcURLInfo build() {
            return new JdbcURLInfo(this.dsType, this.dbUser, this.dbInstance, this.dbPeer, this.dbOptions);
        }
    }
}
